package cn.aitrox.ry.service.oss.interceptor;

import cn.aitrox.ry.service.oss.bean.UrlValidResult;
import cn.aitrox.ry.service.oss.sdk.OssSdk;
import cn.aitrox.ry.util.ArrayUtil;
import cn.aitrox.ry.util.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class UrlValidInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(UrlValidInterceptor.class);

    @Autowired
    private OssKeyThreadLocal osssKeyThreadLocal;

    @Qualifier("localOssSdk")
    @Autowired
    private OssSdk ossSdk;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String origUrl;

        StringBuffer requestURL = request.getRequestURL();

        Map<String, String[]> parameterMap = request.getParameterMap();

        if (ArrayUtil.isEmpty(parameterMap)) {
            origUrl = requestURL.toString();
        } else {
            StringBuffer sb = new StringBuffer();
            sb.append(requestURL.toString()).append("?");
            for (String key : parameterMap.keySet()) {
                sb.append(key).append("=").append(parameterMap.get(key)[0]).append("&");
            }
            origUrl = sb.delete(sb.length() - 1, sb.length()).toString();
        }

        UrlValidResult urlValidResult = ossSdk.validUrl(origUrl);
        if (urlValidResult.getStatus() == HttpStatus.OK) {
            LOG.info(LogUtil.gen("url valid success", "url", origUrl));
            osssKeyThreadLocal.setOssKey(urlValidResult.getOssKey());
            return true;
        } else {
            LOG.error(LogUtil.gen("url valid fail", "url", origUrl, "status", urlValidResult.getStatus() + "", "msg", urlValidResult.getMsg() + ""));
            response.setStatus(urlValidResult.getStatus().value());
            response.getWriter().write(urlValidResult.getMsg());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        osssKeyThreadLocal.clear();
    }
}
